const app = getApp();
const api = require("../../server/Api.js");
const util = require("../../utils/util.js");
const _user = require("../../utils/User.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBar: 0, //状态栏高度
    custom: null, //
    customBar: 0,
    headViewHeight: 0,
    addressName: "",
    imgUrls: [],
    topPosition: "fixed",
    showShareDialog: false,
    list: [], //类目+商品信息
    cart: [], //购物车
    cartCount: 0,
    cartAmount: 0,
    item: {}, //店铺信息
    shopId: app.globalData.shopId,
    showShareInfoDialog: false,
    imagePath: "",
    curPage: 1,
    pageSize: 6,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    that.setData({
      statusBar: app.globalData.StatusBar,
      customBar: app.globalData.CustomBar,
      custom: app.globalData.Custom,
      headViewHeight: (194 - app.globalData.StatusBar - app.globalData.CustomBar) * 2
    })


    if (!app.globalData.loginDone) {
      app.ttLogin().then(res => {
        let userBean = res;
        if (userBean) {
          app.globalData.userBean = res;
          _user.saveUser(userBean);
        }
        app.globalData.loginDone = true
        that.loadFunc(that, options)
      }).catch(msg => {
        app.globalData.userBean = null;
        _user.saveUser(null);
        app.globalData.loginDone = true
        that.loadFunc(that, options)
      });
    } else {
      that.loadFunc(that, options)
    }
  },

  loadFunc(that, options) {
    console.log(options)
    if (options.scene && options.scene != "") {
      let scene = decodeURIComponent(options.scene)
      api.getShareInfoByScene(scene).then(res => {
        if (res.userId) {
          app.globalData.shareUserId = res.userId;
        }
        if (res.type && res.businessId) {
          if (res.type === 1) {
            that.queryShopsAndLocation(res.businessId);
          } else if (res.type === 2) {
            tt.navigateTo({
              url: '../goods-detail/goods-detail?id=' + res.businessId,
            })
            this.queryWxLocation(null)
          } else {
            that.queryShopsAndLocation();
          }
        } else {
          that.queryShopsAndLocation();
        }
      }).catch(msg => {
        console.log(msg)
        app.showToast("获取分享二维码信息失败!")
        that.queryShopsAndLocation();
      })
    } else if (options.id) {
      that.queryShopsAndLocation(options.id);
    } else if (app.globalData.shopId && app.globalData.shopId != "") {
      that.queryShopsAndLocation(app.globalData.shopId);
    } else {
      that.queryShopsAndLocation(app.globalData.shopId);
    }
    if (options.uid) {
      app.globalData.shareUserId = options.uid
    }
    that.queryCart();
  },

  queryShopsAndLocation(shopId) {
    let that = this;
    that.queryWxLocation(function() {
      if (shopId && shopId != "") {
        that.queryShops(shopId);
      } else {
        that.queryShops();
      }
    })
  },

  queryWxLocation(callback) {
    let that = this;
    util.wxAuth('scope.userLocation', function() {
      tt.getLocation({
        type: 'gcj02',
        success: res => {
          that.setData({
            addressName: "当前位置",
            lat: res.latitude,
            lng: res.longitude
          })
          app.globalData.lat = that.data.lat;
          app.globalData.lng = that.data.lng;
          app.globalData.addressName = that.data.addressName;
          if (callback) {
            callback()
          }
          app.globalData.qqmapsdk.reverseGeocoder({
            location: {
              latitude: that.data.lat,
              longitude: that.data.lng
            },
            success: function(res) {
              that.setData({
                addressName: res.result.formatted_addresses.recommend
              })
              app.globalData.addressName = that.data.addressName;
              app.globalData.cityName = res.result.address_component.city
            },
            fail: function(error) {
              app.showToast("获取地理位置失败")
            }
          })
        }
      })
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //let storeDtos = [];
    //api.getStoresByPlatId().then(res => {
    // console.log("获取平台所有店铺", res);
    // let i = 0;
    // let interval = null;
    // interval = setInterval(() => {
    //   if (i >= res.length) {
    //     console.log("批量更新店铺", storeDtos);
    //     setTimeout(() => {
    //       api.batchUpdateStores(storeDtos).then(res => {
    //         console.log("批量更新店铺成功", res);
    //       }).catch(res => {
    //         console.log("批量更新店铺失败", res);
    //       });
    //     }, 3000)
    //     clearInterval(interval)
    //     return;
    //   }
    //   app.globalData.qqmapsdk.geocoder({
    //     address: res[i].address,
    //     success: function(result) {
    //       console.log("获取地址位置", res[i].address, result);
    //       if (result.status == 0) {
    //         result = result.result;
    //         if (result.reliability >= 7) {
    //           storeDtos.push({
    //             id: res[i].id,
    //             latitude: result.location.lat,
    //             longitude: result.location.lng
    //           });
    //           console.log("获取地址位置成功", res[i].address);
    //         } else {
    //           console.log("获取地址位置可信度太低");
    //         }
    //       } else {
    //         console.log("获取地址位置状态异常");
    //       }
    //     },
    //     fail: function(error) {
    //       console.log("获取地理位置失败", error)
    //     }
    //   })
    //   i++;
    // }, 1500)
    //})
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.addressName !== app.globalData.addressName) {
      this.setData({
        addressName: app.globalData.addressName
      })
    }
    if (this.data.lat !== app.globalData.lat || this.data.lng !== app.globalData.lng) {
      this.setData({
        lat: app.globalData.lat,
        lng: app.globalData.lng
      })
    }
    if (this.data.shopId !== app.globalData.shopId && app.globalData.shopId !== 0) {
      this.setData({
        shopId: app.globalData.shopId
      })
      this.refreshData()
    }
    if (app.globalData.loginDone) {
      this.queryCart();
    }
  },
  queryShops: function(shopId) {
    let that = this;
    if (shopId) {
      app.globalData.shopId = shopId;
      that.setData({
        shopId: app.globalData.shopId
      });
      that.refreshData();
    } else {
      let userInfo = app.globalData.userBean;
      let userId = undefined;
      if (userInfo && userInfo.consumerId) {
        userId = userInfo.consumerId
      }
      api.getNearestShop(this.data.lat, this.data.lng, userId).then(res => {
        console.log("获取到最近店铺", res);
        app.globalData.shopId = res.id;
        that.setData({
          shopId: app.globalData.shopId
        });
        that.refreshData();
      }).catch(msg => {
        tt.stopPullDownRefresh();
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    }
  },

  onPullDownRefresh: function(e) {
    var that = this;
    this.queryCart();
    if (that.data.shopId && that.data.shopId != "") {
      this.refreshData();
    } else {
      tt.stopPullDownRefresh()
    }
  },

  refreshData() {
    this.getShopInfo();
    this.getShopBanner();
    this.setData({
      curPage: 1,
      hasMore: true
    })
    this.getCategoryAndGoods();
  },

  getShopInfo: function() {
    const that = this;
    api.getShopInfo(this.data.shopId).then(res => {
      console.log("店铺信息:", res);
      if (res.images && res.images !== "") {
        res.images = app.resetImageUrlByPx(res.images, 100, 100)
      } else {
        res.images = "../../images/logo1.png";
      }
      res.fans = res.fans || "0"
      res.buyExponent = app.setBuyExponent(res.buyExponent)
      //请求成功
      that.setData({
        item: res
      })
      //if (!that.data.jl || that.data.jl == "") {
      app.globalData.qqmapsdk.calculateDistance({
        mode: "straight",
        to: res.latitude + "," + res.longitude,
        success: function(res) {
          if (res.result.elements.length > 0) {
            that.setData({
              jl: app.setMtoKm(res.result.elements[0].distance)
            })
          }
        },
        fail: function(error) {
          console.error("获取距离失败", error);
        },
      });
      //}
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  getShopBanner: function() {
    const that = this;
    api.queryHomeBanner(this.data.shopId).then(res => {
      console.log("轮播图:", res);
      //请求成功
      that.setData({
        imgUrls: res
      })
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  getCategoryAndGoods() {
    let that = this;
    tt.showLoading({
      title: '加载中...',
    })
    let param = {
      pageNumber: that.data.curPage,
      pageSize: that.data.pageSize,
      storeId: that.data.shopId,
      companyId: app.globalData.companyId,
      platformId: app.globalData.platformId,
    }
    api.queryHomeGoods(param).then(res => {
      //api.queryCategoryGoods(that.data.shopId, 10, that.data.curPage, that.data.pageSize).then(res => {
      for (let i = 0; i < res.records.length; i++) {
        res.records[i].spu_image = app.resetImageUrl(res.records[i].spu_image, app.globalData.windowWidth / app.globalData.rpxToPxBl - 48, null);
        res.records[i].dateStr = app.getZtDate(res.records[i].delivery_time);
      }

      console.log("商品信息:", res.records);
      let records = res.records;
      let maxPage = parseInt(res.pages);
      var datas = that.data.curPage === 1 ? [] : that.data.list;
      if (records) {
        datas = datas.concat(records);
      }
      that.setData({
        hasMore: maxPage > that.data.curPage,
        list: datas,
        curPage: that.data.curPage + 1,
      })
      this.setShopCountByCart();
      tt.hideLoading();
      tt.stopPullDownRefresh();
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      tt.hideLoading();
      tt.stopPullDownRefresh();
      app.showToast(message);
    });
  },

  //上拉加载
  onReachBottom: function() {
    if (this.data.hasMore == false) return;
    // tt.showNavigationBarLoading();
    this.getCategoryAndGoods();
  },

  queryCart: function(toShowCartDialog = false) {
    let that = this;
    let userInfo = app.globalData.userBean;
    if (userInfo && userInfo.consumerId) {
      let prams = {
        pageSize: 100,
        pageNumber: 1,
        platformId: app.globalData.platformId,
        userId: userInfo.consumerId
      };
      api.queryCartList(prams).then(res => {
        console.log("购物车:", res);
        that.setData({
          cart: res.records
        })
        let total = 0;
        for (let i = 0; i < res.records.length; i++) {
          for (let j = 0; j < res.records[i].cartVO.length; j++) {
            total += parseInt(res.records[i].cartVO[j].goodsQuantity)
          }
        }
        app.globalData.cartCount = total;
        app.setTabBarBadge();

        this.setShopCountByCart()

      }).catch(msg => {
        console.log(msg);
        app.showToast("获取购物车数量失败!");
      })
    }
  },

  setShopCountByCart: function() {
    if (this.data.list.length > 0) {
      let datas = this.data.list;
      for (let j = 0; j < datas.length; j++) {
        datas[j].goodsQuantity = 0;
        for (let i = 0; i < this.data.cart.length; i++) {
          if (this.data.cart[i].storeId == this.data.shopId) {
            for (let x = 0; x < this.data.cart[i].cartVO.length; x++) {
              if (this.data.cart[i].cartVO[x].skuId === datas[j].sku_id) {
                datas[j].goodsQuantity = this.data.cart[i].cartVO[x].goodsQuantity;
                datas[j].recId = this.data.cart[i].cartVO[x].recId;
                break;
              }
            }
            break;
          }
        }
      }
    }
    console.log("重置购物车数量", this.data.list)
    this.setData({
      list: this.data.list
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let that = this;
    let userId = "";
    let userInfo = app.globalData.userBean;
    if (userInfo && userInfo.consumerId) {
      userId = userInfo.consumerId
    }
    return {
      title: '好获拼拼-' + that.data.item.storeName,
      path: 'pages/index/index?id=' + that.data.shopId + "&uid=" + userId,
      imageUrl: 'https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/index_share.png',
      success: function(res) {
        tt.showToast('转发成功');
      },
      fail: function() {
        tt.showToast('转发失败');
      }
    }
  },

  onPageScroll(e) {
    // if (e.scrollTop > 0) {
    //   if (this.data.topPosition === "absolute") {
    //     this.setData({
    //       topPosition: "fixed"
    //     })
    //   }
    // } else {
    //   if (this.data.topPosition === "fixed") {
    //     this.setData({
    //       topPosition: "absolute"
    //     })
    //   }
    // }
  },
  showShareDialog() {
    let that = this;
    tt.hideTabBar({
      success: function() {
        that.setData({
          showShareDialog: true
        })
      }
    })
  },
  hiddenShareDialog() {
    let that = this;
    // wx.showTabBar({
    //   success: function() {
    //     that.setData({
    //       showShareDialog: false
    //     })
    //   }
    // })
  },
  refreshCart: function() {
    this.queryCart(false);
  },
  tapSwiper(e) {
    console.log(e)
    if (e.currentTarget.dataset.item.jumpType == 1) {
      if (e.currentTarget.dataset.item.jumpUrl && e.currentTarget.dataset.item.jumpUrl != "") {
        tt.navigateTo({
          url: '../goods-detail/goods-detail?id=' + e.currentTarget.dataset.item.jumpUrl,
        })
      } else {
        app.showToast("该商品已下架")
      }
    }
    // else if (e.currentTarget.dataset.item.jumpType == 2) {
    //   wx.navigateTo({
    //     url: '../web-view/web-view?src=' + encodeURIComponent(e.currentTarget.dataset.item.jumpUrl) + "&name=" + e.currentTarget.dataset.item.name
    //   })
    // }
    // if (e.currentTarget.dataset.item.name === "供应商招募") {
    //   wx.navigateTo({
    //     url: '../../joinUs/pages/supplier/index',
    //   })
    // } else if (e.currentTarget.dataset.item.name === "团长招募") {
    //   wx.navigateTo({
    //     url: '../../joinUs/pages/shop/index',
    //   })
    // }
  },
  onSearch() {
    app.showToast("商品搜索功能暂未开放")
  }
})